<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>任务管理</el-breadcrumb-item>
      <el-breadcrumb-item>任务展示</el-breadcrumb-item>
    </el-breadcrumb>
    <div style="margin-top: 30px">
      <el-form :inline="true" :model="taskForm" ref="taskForm" class="demo-form-inline">
        <el-form-item label="任务">
          <el-input v-model="taskForm.name" placeholder="任务名称"></el-input>
        </el-form-item>
        <el-form-item label="任务截止日期">
          <el-date-picker
            v-model="start2endTime"
            type="datetimerange"
            :picker-options="pickerOptions"
            value-format="yyyy-MM-dd hh:mm:ss"
            :formatter="dateFormat"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="任务状态">
          <el-select clearable="clearable" v-model="taskForm.isDeal" placeholder="任务状态">
            <el-option label="全部" value=""></el-option>
            <el-option label="已接受" value="1"></el-option>
            <el-option label="未接受" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务等级">
          <el-select clearable="clearable" v-model="taskForm.isUrgent" placeholder="任务等级">
            <el-option label="全部" value=""></el-option>
            <el-option label="紧急" value="1"></el-option>
            <el-option label="一般" value="0"></el-option>
            <el-option label="过期" value="-1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getTasks">查询</el-button>
        </el-form-item>
      </el-form>
      <!-- 新增，发布任务 -->
      <el-row>
        <el-button type="primary" plain @click="dialogFormVisible=true">发布任务</el-button>
        <el-button :disabled="isAllDel" type="danger" plain @click="toggleSelection">批量删除</el-button>
      </el-row>
      <el-dialog v-dialog-drag title="发布任务" :visible.sync="dialogFormVisible">
        <div>
          <el-form :model="taskForm" :rules="rules" ref="taskForm" label-width="100px">
            <el-form-item label="是否自定义" prop="isSelfTask">
              <el-switch v-model="taskForm.isSelfTask"></el-switch>
            </el-form-item>
            <el-form-item label="任务名称" prop="name">
              <el-input clearable="clearable" v-if="taskForm.isSelfTask" v-model="taskForm.name"></el-input>
              <el-select clearable="clearable" v-else v-model="taskForm.name" placeholder="任务类型">
                <el-option label="代课" value="代课"></el-option>
                <el-option label="代取快递" value="代取快递"></el-option>
                <el-option label="代取外卖" value="代取外卖"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="任务时间" required>
              <el-date-picker
                v-model="taskForm.start2endTime"
                type="datetimerange"
                :picker-options="pickerOptions"
                value-format="yyyy-MM-dd hh:mm:ss"
                :formatter="dateFormat"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                align="right">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="是否紧急" prop="isUrgent">
              <el-switch v-model="taskForm.isUrgent"></el-switch>
            </el-form-item>
            <el-form-item label="任务报酬" prop="reward">
              <el-input type="number" clearable="clearable" v-model="taskForm.reward"></el-input>
            </el-form-item>
            <el-form-item label="任务描述" prop="content">
              <el-input type="textarea" v-model="taskForm.content"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div style="border-radius: 2px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);">
      <el-table
        ref="multipleTable"
        v-loading="isLoading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        :data="tableData"
        style="width: 100%; margin-top: 10px;"
        max-height="400"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column
          fixed
          prop="name"
          label="任务名称"
          width="150">
        </el-table-column>
        <el-table-column
          prop="reward"
          label="报酬"
          width="120">
        </el-table-column>
        <el-table-column
          prop="isUrgent"
          label="是否紧急"
          width="120">
        </el-table-column>
        <el-table-column
          prop="isDeal"
          label="是否处理解决"
          width="120">
        </el-table-column>
        <el-table-column
          prop="imgUrl"
          label="相关图片"
          width="300">
        </el-table-column>
        <el-table-column
          prop="deadline"
          label="截止时间"
          :formatter="dateFormat"
          width="200">
        </el-table-column>
        <el-table-column
          prop="content"
          label="描述"
          width="600">
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="200">
          <template slot-scope="scope">
            <el-button
              @click.native.prevent="deleteRow(scope.$index, tableData)"
              type="text"
              size="small">
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageTotal">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import loading from "@/components/loading";
import store from "@/store";
import {del} from '@/api/task';

export default {
  inject: ['reload'],
  name: "tasks",
  components: { loading },
  mounted() {
    this.isLoading = true
    this.getTasks()
  },
  methods: {
    getTasks() {
      this.tableData = []
      this.taskForm['pageNum'] = this.pageNum
      this.taskForm['pageSize'] = this.pageSize
      this.taskForm['creatTime'] = this.start2endTime[0]
      this.taskForm['endTime'] = this.start2endTime[1]
      console.log(this.taskForm,'我添加了分页')
      this.$store.dispatch('task/getInfo', this.taskForm).then(response =>{
        this.isLoading = false;
        this.tableData = response.data.list;
        this.pageNum = response.data.pageNum;
        this.pageSize = response.data.pageSize;
        this.pageTotal = response.data.total;
        console.log('this page total1: ', this.pageTotal, response.data.total)
      })
      console.log('this page total2: ', this.pageTotal)
    },
    onSubmit() {
      console.log('submit!');
    },
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },
    // 时间戳转换成时间
// 使用element table组件中的formatter属性，传入一个函数
    timestampToTime (row, column) {
      var date = new Date(row[column.property]) //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + '-'
      var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'
      var D = date.getDate() + ' '
      var h = date.getHours() + ':'
      var m = date.getMinutes() + ':'
      var s = date.getSeconds()
      return Y+M+D+h+m+s
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.isLoading = true
      this.taskForm['pageNum'] = this.pageNum
      this.taskForm['pageSize'] = val
      console.log(this.taskForm,'我添加了分页')
      this.$store.dispatch('task/getInfo', this.taskForm).then(response =>{
        this.isLoading = false;
        this.tableData = response.data.list;
        this.pageNum = response.data.pageNum;
        this.pageSize = response.data.pageSize;
        this.pageTotal = response.data.total;
      })
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.isLoading = true
      this.taskForm['pageNum'] = val
      this.taskForm['pageSize'] = this.pageSize
      this.$store.dispatch('task/getInfo', this.taskForm).then(response =>{
        this.isLoading = false;
        this.tableData = response.data.list;
        this.pageNum = response.data.pageNum;
        this.pageSize = response.data.pageSize;
        this.pageTotal = response.data.total;
      })
    },
    async toggleSelection() {
      const vals = this.delIds
      for (let i = 0; i < vals.length; i++) {
        await del(vals[i])
      }
      this.$notify({
        title: '成功',
        message: '删除成功，请刷新看一看叭。',
        type:'success'
      })
      this.reload()
    },
    handleSelectionChange(val) {
      this.delIds = []
      if (val.length > 0){
        this.isAllDel = !this.isAllDel
        console.log(val)
        this.multipleSelection = val;
      }else{
        this.isAllDel = true
      }
      for (let i = 0; i < val.length; i++) {
        this.delIds.push(val[i].id)
      }
    },
    submitForm() {
      this.$refs.taskForm.validate((valid) => {
        if (valid) {
          if (this.taskForm.isDeal) {
            this.taskForm.isDeal = 1
          }else{
            this.taskForm.isDeal = 0
          }
          if (this.taskForm.isUrgent) {
            this.taskForm.isUrgent = 1
          }else{
            this.taskForm.isUrgent = 0
          }
          this.taskForm.createTime = this.taskForm.start2endTime[0]
          this.taskForm.deadline = this.taskForm.start2endTime[1]
          // get user
          store.dispatch('user/getInfo').then(data => {
            //
            this.taskForm.creator = data.id
            this.$store.dispatch('task/create', this.taskForm)
              .then(() => {
                this.dialogFormVisible = false
                this.$router.push('/main/tasks')
              })
              .catch(() => {
                this.loading = false
              })
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    dateFormat(row, column, cellValue, index) {
      console.log(row, column, cellValue, index)
      const daterc = row[column.property]
      if (daterc != null) {
        var date = new Date(daterc);
        var year = date.getFullYear();
        /* 在日期格式中，月份是从0开始，11结束，因此要加0
         * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
         * */
        var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
        var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
        var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        // 拼接
        return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
      }
    },
    //判断数据是否为空值，为空返回true,有值为false
    isNull(data) {
      if (!data) return true;
      if (JSON.stringify(data) === '{}') return true;
      if (JSON.stringify(data) === '[]') return true;
      return false;
    }
  },
  data() {
    return {
      //
      delIds: [],
      //
      isAllDel: true,
      // task
      isSelfTask: false,
      pageNum: 1,
      pageSize: 5,
      pageTotal: 5,
      start2endTime: [],
      taskForm: {
        name: '',
        isUrgent: '',
        creatTime: '',
        endTime: '',
        content: '',
        isDeal: '',
        reward: 100,
        creator: '',
        deadline: '',
        remark: '-',
        imgUrl: 'easy-help/upload/file/img/'
      },
      rules: {
        name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],

        content: [
          { required: true, message: '请填写活动形式', trigger: 'blur' }
        ]
      },
      //
      dialogTableVisible: false,
      dialogFormVisible: false,
      // ++++++++++++++++++++++++
      multipleSelection: [],
      isLoading: false,
      formInline: {
        taskName: '',
        isAccept: false,
        level: ''
      },
      tableData: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      value1: [new Date(2000, 10, 10, 10, 10), new Date(2000, 10, 11, 10, 10)],
      value2: ''
    }
  }
}
</script>

<style scoped>

</style>
